import React, { useState, useEffect } from 'react';
import { ck_float, to_float, cline, uReal, useKForm, KInput, useHigh, GridTable, useCmd, WaitUmd, MainView, BtTxt, KFind, ck_empty,
    KSelect, is_empty, DlgFind, KSwitch, PanelTitle, Btn, loc } from 'sui';
import { useAccess } from 'cache';
import { TaskView } from './task/view';
import { PBox } from './pbox';
import { load_his, reload, load_tech } from './cmd';
import { DlgLog } from './ctl';
import { User } from 'cache';

const PairView = () => {
    const [open_his, openHis] = useState(false);
    const [open_log, openLog] = useState(false);
    const [main, setMain] = useState();
    const [his, setHis] = useState();
    const [dw_lst, dwLst] = useState();
    const [high] = useHigh(252, 100);
    const [no_acc] = useAccess();
    const umd = useCmd();
    const form = useKForm(null, {
        diff: 2,
        w: 0.5,
        range: 1,
    });

    useEffect(() => {
        reload(null, setMain);
        load_tech(dwLst);
        load_his(setHis);
    }, []);

    const hreturn = () => {
        reload(null, setMain);
        umd.hreturn();
    };

    if (umd.isFin("task")) {
        return <TaskView cur={umd.cur} hreturn={hreturn}/>;
    }

    if (umd.isFin("pbox")) {
        return <PBox hreturn={() => umd.hreturn()}/>;
    }

    const hHis = (v) => {
        if (is_empty(his)) {
            return;
        }

        const f = his.find(d => d.sn === v);
        if (!f) {
            return;
        }

        const cmd = f.v;
        if (cmd["other"]) {
            cmd["stsn"] = cmd["other"];
            cmd["other"] = "Y";
        }

        form.setValue(cmd);
    };

    const hCalc = () => {
        const ck = {
            w : v => ck_float(v),
            diff : v => ck_float(v),
            base : v => ck_float(v),
            range : v => ck_float(v),
            tsn : v => ck_empty(v),
            dmin: v => ck_float(v),
            dmax: v => {
                const e = ck_float(v);
                if (e) {
                    return e;
                }

                const a = to_float(form.get("dmin"));
                const b = to_float(form.get("dmax"));

                if (b < a) {
                    return loc("l_705");
                }

                return null;
            },
            kmin: v => ck_float(v),
            kmax: v => {
                const e = ck_float(v);
                if (e) {
                    return e;
                }

                const a = to_float(form.get("kmin"));
                const b = to_float(form.get("kmax"));

                if (b < a) {
                    return loc("l_705");
                }

                return null;
            },
            stsn: v => {
                const other = form.get("other");
                if (other !== "Y") {
                    return null;
                }

                let tsn = form.get("tsn");
                tsn = tsn.split("-");

                let stsn = v.split("-");

                if (tsn[0] !== stsn[0]) {
                    return loc("l_846");
                }

                return null;
            },
            tp: v => {
                const other = form.get("other");
                if (other !== "Y") {
                    return null;
                }

                return ck_empty(v);
            }
        };

        if (form.isErr(ck)) {
            return;
        }

        umd.startWait();

        const opt = {
            w: to_float(form.get("w")),
            diff: to_float(form.get("diff")),
            base: to_float(form.get("base")),
            range: to_float(form.get("range")),
            tsn: form.get("tsn"),
            dmin: to_float(form.get("dmin")),
            dmax: to_float(form.get("dmax")),
            kmin: to_float(form.get("kmin")),
            kmax: to_float(form.get("kmax")),
        };

        const pbox = form.get("pbox");
        if (pbox === "Y") {
            opt["pbox"] = true;
            opt["usn"] = User.userName();
        }

        const other = form.get("other");
        if (other === "Y") {
            opt["other"] = form.get("stsn");
            opt["tp"] = form.get("tp");
        }

        uReal(null, "pair/calc",
            {
                line: cline(),
                ...opt,
            },
            r => {
                load_his(setHis);
                reload(umd.endWait, setMain);
            },
            e => umd.setErr(loc("l_704")), true);
    };

    const col = [
        {name: loc("l_193"), key: 'index', width: 70, frozen: true},
        {name: loc("l_238"), key: 'e_opt', width: 120, frozen: true, formatter: (props) => {
            const d = props.row;
            return (
                <div className="inline-flex">
                    <BtTxt hcmd={() => umd.pact(null, d, "task")}>{loc("l_706")}</BtTxt>
                </div>
            );
        }},
        {name: loc("l_363"), key: 'sn', width: 200},
        {name: loc("l_702"), key: 'pnum', width: 230},
    ];

    const lst_other = [
        {name: loc("l_900"), sn: 'both'},
        {name: loc("l_808"), sn: 'inner'},
        {name: loc("l_809"), sn: 'outer'},
    ];

    const dis = () => form.get("other") !== "Y";

    return (
        <MainView>
            <PanelTitle left={loc("l_736")} cl="gray">
                <div className="flex flex-row">
                    <Btn className="mr-4 mb-6 mt-2" disabled={no_acc("da")} hcmd={() => hCalc()}>{loc("l_701")}</Btn>
                    <div className="flex flex-col mb-4">
                        <div className="inline-flex items-center">
                            <KFind label={loc("l_694")} form={form} name="tsn" margin="dense" width="w-56" list={dw_lst}/>
                            <KInput label={loc("l_693")} form={form} name="diff" mg="dense" width="w-24" className="mx-4"/>
                            <KInput label={loc("l_692")} form={form} name="w" mg="dense" width="w-24"/>
                            <div className="inline-flex items-center ml-4 px-2 border-blue-600 border">
                                <span className="text-base mr-4 mt-1">{loc("l_695")}</span>
                                <KInput label={loc("l_699")} form={form} name="base" mg="dense" width="w-20"/>
                                <span className="text-base mx-4">{"+/-"}</span>
                                <KInput label={loc("l_700")} form={form} name="range" mg="dense" width="w-20"/>
                            </div>
                            <div className="inline-flex items-center ml-4 px-2 border-blue-600 border">
                                <span className="text-base mr-4 mt-1">{loc("l_783")}</span>
                                <KInput label={loc("l_696")} form={form} name="dmin" mg="dense" width="w-20"/>
                                <KInput label={loc("l_646")} form={form} name="dmax" mg="dense" width="w-20" className="ml-2"/>
                            </div>
                            <div className="inline-flex items-center px-2 ml-4 border-blue-600 border">
                                <span className="text-base mr-4 mt-1">{loc("l_784")}</span>
                                <KInput label={loc("l_696")} form={form} name="kmin" mg="dense" width="w-20"/>
                                <KInput label={loc("l_646")} form={form} name="kmax" mg="dense" width="w-20" className="ml-2"/>
                            </div>
                        </div>
                        <div className="inline-flex mt-4 items-center">
                            <Btn className="mr-4" color="green" disabled={no_acc("da")} hcmd={() => openHis(true)}>{loc("l_861")}</Btn>
                            <Btn className="mr-4" disabled={no_acc("da")} hcmd={() => openLog(true)}>{loc("l_862")}</Btn>
                            <KSwitch form={form} name="other" className="mr-4">{loc("l_845")}</KSwitch>
                            <KSelect form={form} name="tp" className="mr-4 mt-2" mg="dense" lst={lst_other} disabled={dis()} label={loc("l_229")}/>
                            <KFind label={loc("l_694")} form={form} name="stsn" margin="dense" width="w-56" list={dw_lst} disabled={dis()}/>
                            <KSwitch form={form} name="pbox" className="ml-2">{loc("l_799")}</KSwitch>
                            <Btn className="ml-4" disabled={form.get("pbox") !== "Y"} hcmd={() => umd.pact(null, null, "pbox")}>{loc("l_800")}</Btn>
                        </div>
                    </div>
                </div>
            </PanelTitle>
            <GridTable col={col} row={main} high={high}/>
            <DlgFind open={open_his} setOpen={openHis} hcmd={hHis} title={loc("l_861")} main={his} c1={loc("l_177")}/>
            <DlgLog open={open_log} setOpen={openLog} data={his}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {PairView};
